<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/*
 * 秘钥加密解密算法
 * $str = 'abc';
 * $key = 'www.fyunw.com';
 * $token = encrypt($str, 'E', $key);
 * echo '加密:'.encrypt($str, 'E', $key);
 * echo '解密：'.encrypt($str, 'D', $key);
 * */

use app\admin\helper\LangHelper;


function countWords($str){
    $str=strip_tags($str);
    $str=str_replace(' ','',$str);//过滤空格
    $str=mb_strlen($str, 'utf8');
    return $str;
}

function export($sheetname,$data,$header){
    $name = $sheetname . date('Ymd') . ".csv";
    $name = mb_convert_encoding($name, "gbk", "utf-8");
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename={$name}");
    header("Pragma: no-cache");
    header("Expires: 0");
    $outputBuffer = fopen("php://output", 'w');
    if(!empty($header)){
        //先遍历表头
        $excelHeader = [];
        foreach ($header as $v) {
            if (!isset($v['field']) || $v['field'] == 'op')
                continue;
            $excelHeader[$v['field']] = $v['title'];

        }
        foreach($excelHeader as $field=>$title){
            $excelHeader[$field] =mb_convert_encoding($title, "gbk", "utf-8"); // CSV的Excel支持GBK编码，一定要转换，否则乱码
        }
        fputcsv($outputBuffer, $excelHeader);
        if(!empty($data)){
            foreach($data as $value){
                $value_tmp = [];
                foreach($excelHeader as $field=>$title){
                    $value_tmp[$field] =isset($value[$field])? mb_convert_encoding($value[$field], "gbk", "utf-8"):'';
                }
                fputcsv($outputBuffer, $value_tmp);
            }
        }
        fclose($outputBuffer);
    }
    exit;
}

/**
 * 反射调用类
 * @param $class
 * @param $func
 * @param array ...$args
 * @return mixed
 */
function reflection($class,$func, ...$args){
    $ref_class = new \ReflectionClass($class); // get反射类名
    $instance  = $ref_class->newInstance(...$args);    // get反射类中的私有变量
    $method = $ref_class->getmethod($func);    // 获取反射类名中的方法
    $method->setAccessible(true);              // 设置可访问性
    $result = $method->invoke($instance, ...$args); // 执行方法
    return $result;                            // 返回执行结果
}

function encrypt($string, $operation, $key = '')
{
    $key = md5($key);
    $key_length = strlen($key);
    $string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string;
    $string_length = strlen($string);
    $rndkey = $box = array();
    $result = '';
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($key[$i % $key_length]);
        $box[$i] = $i;
    }
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if ($operation == 'D') {
        if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
            return substr($result, 8);
        } else {
            return '';
        }
    } else {
        return str_replace('=', '', base64_encode($result));
    }
}

/*
 * 随机生成秘钥
 * */
function random_char($length = 8, $chars = null)
{
    if (empty($chars)) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    }
    $chars = str_shuffle($chars);
    $num = $length < strlen($chars) - 1 ? $length : strlen($chars) - 1;
    return substr($chars, 0, $num);
}

/*
 * 发送邮件
 * $to 发送给
 * $subject 主题
 * $content 正文
 * */
function email($to, $subject, $content,$config = null)
{
    require VENDOR_PATH . 'phpmailer/Mail.class.php';
    $mail = new PHPMailer();
    $mail->IsSMTP();
    $mail->IsHTML();
    //如果config不为空 优先使用该配置
    if (empty($config)) {
        $config = (new \app\admin\model\EmailM())->listData();
    }
    $mail->CharSet = $config['encoding'];
    foreach ((array)$to as $k => $v) {
        $mail->AddAddress($v);//设置收件的地址
    }

    if ($config['smtp_auth']) {
        $mail->SMTPAuth = true;
    }
    $mail->SMTPSecure = $config['smtp_secure'];

    $mail->Body = $content;
    $mail->From = $config['from'];
    $mail->FromName = $config['formname'];
    $mail->Subject = $subject;
    $mail->Host = $config['host'];
    $mail->Port = $config['port'];
    $mail->Username = $config['username'];
    $mail->Password = $config['password'];
    return $mail->Send();

}

/*
 * CURL获取JSON数据
 * */
function curl_api($url,$curlPost){
    $ch=curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_HEADER,0);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    //设置是通过post还是get方法
    curl_setopt($ch,CURLOPT_POST,1);
    //传递的变量
    curl_setopt($ch,CURLOPT_POSTFIELDS,$curlPost);
    $data = curl_exec($ch);
    curl_close($ch);
    $data=json_decode($data);
    return $data;
}

/*
 * 获取客户端IP地址
 * */
function getIP(){
    global $ip;
    if (getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if(getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if(getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    else $ip = "Unknow IP";
    return $ip;
}

/**
 * 日志记录
 * @param $log_content
 * @param $tag
 */
function pr_log($log_content,$tag) {
    $log_filename = ROOT_PATH .'runtime'.DS.'logs'.DS .$tag.DS.date("Ym").DS;
    file_exists($log_filename) ?: mkdir($log_filename, 0755, true);
    if(is_array($log_content)){
        $log_content = json_encode($log_content,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    }
    file_put_contents($log_filename.date("d").'.log', '['.date("Y-m-d H:i:s").']' .PHP_EOL . $log_content . PHP_EOL."------------------------ --------------------------".PHP_EOL, FILE_APPEND);
}

/*
 * 操作成功
 * */
function op_success($extra=''){
    $result=[
        'code'=>1,
        'msg'=>'__op_success__',
        'extra'=> $extra
    ];
    $result = LangHelper::convertLang($result);
    return $result;
}

/*
 * 操作失败
 * */
function op_fail($extra=''){
    $result=[
        'code'=>0,
        'msg'=>'__op_failed__',
        'extra'=> $extra
    ];
    $result = LangHelper::convertLang($result);
    return $result;
}

/*
 * 数据库修改 没有字段变化
 * */
function op_nochange($extra=''){
    $result=[
        'code'=>0,
        'msg'=>'__op_nochange__',
        'extra'=> $extra
    ];
    $result = LangHelper::convertLang($result);
    return $result;
}

/*
 * 超级管理员
 * */
function op_superadmin(){
    $result=[
        'code'=>0,
        'msg'=>'__need_root__'
    ];
    $result = LangHelper::convertLang($result);
    return $result;
}

/*
 * 权限验证失败
 * */
function op_noper(){
    $result=[
        'code'=>0,
        'msg'=>'__un_acl__'
    ];
    $result = LangHelper::convertLang($result);
    return $result;
}

/*
 * 自定义消息
 * */
function op_msg($code,$msg){
    $result=[
        'code'=>$code,
        'msg'=>$msg
    ];
    return $result;
}

/*
 * echo 无权限页面
 * */
function forbidden($css_js){
    $result=
        <<<EOF
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>NO AUTH*******</title>
    {$css_js}
    <style>
        body{
            background-color: #f5f5f5;
        }
    </style>
</head>
<body >
<div class="yui_height well">
    <h1 class="grey lighter smaller">
        <span class="blue bigger-125">
            <i class="icon-random"></i>
            500
        </span>
        没有权限
    </h1>

    <hr>
    <h3 class="lighter smaller">
        高度机密
        <br>
        严禁未经授权的人员进行访问
        <br>
        肇事者将被监控，定位并处理
    </h3>

    <div class="space"></div>
    <div>
        <h4 class="lighter smaller">警告：</h4>

        <ul class="list-unstyled spaced inline bigger-110 margin-15">
            <li>
                <i class="icon-hand-right blue"></i>
                你已经被警告过了。
            </li>

            <li>
                <i class="icon-hand-right blue"></i>
                任何未经授权之人员访问该文档将立即被BERRYMAN-LANGFORD模因抹杀触媒处决。在未接种合适模因疫苗的情況下向下滚动页面将立刻导致心脏骤停死亡。
            </li>
        </ul>
    </div>

</div>
</body>
</html>
EOF;
    return $result;
}

/*
 * js css 引入
 * */
function js_css(){
    $result=
        <<<EOF
<link rel="shortcut icon" href="/static/images/ico.jpg" media="screen" />

<link href="/static/plugin/ace/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="/static/plugin/ace/css/font-awesome.min.css" />

<!--[if IE 7]>
<link rel="stylesheet" href="/static/plugin/ace//css/font-awesome-ie7.min.css" />
<![endif]-->
<link rel="stylesheet" href="/static/plugin/ace/font/fontawesome-webfont.woff" />

<!-- ace styles -->

<link rel="stylesheet" href="/static/plugin/ace/css/ace.min.css" />
<link rel="stylesheet" href="/static/plugin/ace/css/ace-rtl.min.css" />
<link rel="stylesheet" href="/static/plugin/ace/css/ace-skins.min.css" />

<!--[if lte IE 8]>
<link rel="stylesheet" href="/static/plugin/ace/css/ace-ie.min.css" />
<![endif]-->
<script type="text/javascript" src="/static/js/jquery.min.js"></script>
<!-- inline styles related to this page -->
<link href="/static/plugin/layer/theme/default/layer.css">
<script type="text/javascript" src="/static/plugin/layer/layer.js"></script>
<!-- ace settings handler -->


<script src="/static/plugin/ace/js/ace-extra.min.js"></script>

<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->

<!--[if lt IE 9]>
<script src="/static/plugin/ace/js/html5shiv.js"></script>
<script src="/static/plugin/ace/js/respond.min.js"></script>
<![endif]-->


<script src="/static/plugin/ace/js/bootstrap.min.js"></script>
<script src="/static/plugin/ace/js/typeahead-bs2.min.js"></script>

<!-- page specific plugin scripts -->

<!--[if lte IE 8]>
<script src="/static/plugin/ace/js/excanvas.min.js"></script>
<![endif]-->

<script src="/static/plugin/ace/js/jquery-ui-1.10.3.custom.min.js"></script>
<script src="/static/plugin/ace/js/jquery.ui.touch-punch.min.js"></script>
<script src="/static/plugin/ace/js/jquery.slimscroll.min.js"></script>
<script src="/static/plugin/ace/js/jquery.easy-pie-chart.min.js"></script>
<script src="/static/plugin/ace/js/jquery.sparkline.min.js"></script>
<script src="/static/plugin/ace/js/flot/jquery.flot.min.js"></script>
<script src="/static/plugin/ace/js/flot/jquery.flot.pie.min.js"></script>
<script src="/static/plugin/ace/js/flot/jquery.flot.resize.min.js"></script>

<script src="/static/plugin/ace/js/ace-elements.min.js"></script>
<script src="/static/plugin/ace/js/ace.min.js"></script>
EOF;
    return $result;
}